package com.springboot.controller;
import com.springboot.pojo.Count;
import com.springboot.pojo.Result;
import com.springboot.pojo.User;
import com.springboot.vo.UserLoginVO;
import com.springboot.properties.JwtProperties;
import com.springboot.service.UserService;
import com.springboot.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {//@RequestBody注解会将实体或集合类对象自动转换为json格式数据，前端不用转换；
        log.info("用户登录");
        Count u = userService.login(user);
        if (u.getNumber()==-2){
            return Result.error("尝试次数已达到上限,请联系超级管理员");
        }
        if (u.getNumber() == -1) {
            return Result.error("找不到此用户");
        }
        if (u.getNumber() == 0) {
            return Result.error("身份信息或密码错误",u.getCount());
        }
        if (u.getNumber() == 1) {
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("userStation", user.getStation());
            String token = JwtUtil.createJWT(
                    jwtProperties.getAdminSecretKey(),
                    jwtProperties.getAdminTtl(),
                    claims);
            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .station(user.getStation())
                    .identity(user.getIdentity())
                    .token(token)
                    .build();
            return Result.success(userLoginVO,"登录成功，欢迎使用DPS系统");
        }
        return Result.error("身份信息或密码错误");
    }
    @PostMapping("/forget")
    public Result forget(@RequestBody User user) {//@RequestBody注解会将实体或集合类对象自动转换为json格式数据，前端不用转换；
        log.info("用户忘记密码");
        boolean u = userService.forget(user);
        if(u){
            return Result.success("提交成功");
        }
        return Result.error("请输入正确的用户信息");
    }

}

